<template>
  <div
    class="manage-shopping-tab1"
    v-loading="loading"
    element-loading-text="加载中..."
  >
    <div class="manage-shopping-title">
      <div class="manage-shopping-title-left" style="white-space: nowrap">
        <el-form inline>
          <el-form-item>
            <el-tree-select
              style="width: 220px"
              default-expand-all
              node-key="id"
              filterable
              v-model="searchForm.cateid"
              :data="classOptions"
              check-strictly
              clearable
              :render-after-expand="false"
              :props="{
                label: 'name',
                children: 'sub',
              }"
              placeholder="商品分类"
            >
            </el-tree-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="searchForm.name"
              placeholder="商品名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="searchForm.code"
              placeholder="商品编码"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-select v-model="searchForm.status" clearable placeholder="状态">
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="searchForm.is_integral"
              clearable
              placeholder="积分专区商品"
            >
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item style="width: 180px">
            <el-button type="primary" @click="searchFun">查询</el-button>
            <el-button @click="resetFun">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="manage-shopping-title-right" style="white-space: nowrap">
        <el-button @click="uploadFun">
          <template #icon>
            <el-icon>
              <IEpUpload />
            </el-icon>
          </template>
          导入
        </el-button>
        <el-button type="primary" :icon="Plus" @click="addDeptFun('add')">
          添加
        </el-button>
      </div>
    </div>
    <div class="manage-shopping-table">
      <el-table
        @selection-change="handleSelectionChange"
        border
        stripe
        :data="tableData"
        :height="store.tableHeight - 90"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column prop="id" label="ID" width="55" align="center" />
        <el-table-column prop="goods_name" label="商品名称" width="500">
          <template #default="{ row }">
            <div class="manage-info">
              <el-image
                :preview-teleported="true"
                style="width: 50px; min-width: 50px; height: 50px"
                :src="imgSrc(row.cover)"
                :zoom-rate="1.2"
                :preview-src-list="[imgSrc(row.cover)]"
                :initial-index="4"
                fit="cover"
                class="img-box"
              />
              <div class="right">
                <div>
                  <label>商品名称：</label>
                  <span>{{ row.goods_name }} </span>
                </div>
                <div>
                  <label>商品编号：</label>
                  <span>{{ row.code }} </span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="code" label="商品分类">
          <template #default="{ row }">
            <div>
              {{ row.cate?.name }}
            </div>
            <div>
              <el-tag
                style="margin-right: 5px"
                v-for="item in row.marks"
                effect="dark"
                size="small"
              >
                {{ item }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="推荐">
          <template #default="{ row }">
            <el-tag v-if="row.state_hot == 1"> 是 </el-tag>
            <el-tag v-else type="warning">否</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="库存" show-overflow-tooltip>
          <template #default="{ row }">
            <div>累计库存： {{ row.stock_total }}</div>
            <div>剩余库存： {{ row.stock_total - row.stock_sales }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-text="上架"
              :active-value="1"
              inactive-text="下架"
              :inactive-value="0"
              inline-prompt
              @change="statusFun(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="updateDeptFun('update', row)"
            >
              编辑
            </el-button>
            <el-button type="success" link @click="addInventory(row)">
              添加库存
            </el-button>
            <el-button type="warning" link @click="logFun(row)">
              库存记录
            </el-button>
            <el-button type="danger" link @click="delFun(row)">删除</el-button>
            <el-button type="primary" link @click="copyFun(row)">
              复制
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="manage-shopping-table-foot" style="margin-top: 10px">
        <div></div>
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <div></div>
      </div>
    </div>
  </div>
  <addDialog ref="addDialogRef" @refreshList="refreshList" />
  <addNumber ref="addNumberRef" @refreshList="refreshList" />
  <uploadPage ref="uploadPageRef" @updateList="updateList" />
</template>
<script setup>
import { Plus } from "@element-plus/icons-vue";
import { useCounterStore } from "@/stores/counter.js";
import {
  listApi,
  delApi,
  stateApi,
  copyApi,
} from "@/plugins/api/shopping/manage";
import { listApi as classApi } from "@/plugins/api/shopping/class";
import addDialog from "./DialogManage.vue";
import addNumber from "./DialogManage-add.vue";
import uploadPage from "./ManageTab1-UploadFile.vue";

const store = useCounterStore();
const router = useRouter();
let tableData = ref([]);

let loading = ref(false);
let searchForm = ref({});
function searchFun() {
  currentPage.value = 1;
  selectData.value = [];
  tableData.value = [];
  getData();
}
function resetFun() {
  currentPage.value = 1;
  searchForm.value = {};
  tableData.value = [];
  selectData.value = [];
  getData();
}
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const handleSizeChange = (val) => {
  pageSize.value = val;
  selectData.value = [];
  getData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  selectData.value = [];
  getData();
};
function getData() {
  loading.value = true;
  let obj = Object.assign(
    {
      page: currentPage.value,
      pageSize: pageSize.value,
    },
    searchForm.value
  );
  listApi(obj)
    .then((data) => {
      tableData.value = data.list;
      total.value = data.page.total;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}
let selectData = ref([]);
function handleSelectionChange(val) {
  selectData.value = val;
}
function delAllFun() {
  if (
    selectData.value.some((item) => {
      return item.type == "系统预设";
    })
  ) {
    return ElMessage.warning("请选择规格类型为'用户自建'的数据进行删除！");
  } else {
    ElMessageBox.confirm("确认批量删除选中的数据，是否继续?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        let arr = selectData.value.map((ele) => {
          return ele.id;
        });
        delApi({
          id: arr.join(","),
        }).then(() => {
          ElMessage({
            type: "success",
            message: "删除成功！",
          });
          selectData.value = [];
          getData();
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消。",
        });
      });
  }
}

let addDialogRef = ref(null);
function addDeptFun(type) {
  addDialogRef.value.initFun(type);
}
function updateDeptFun(type, row) {
  addDialogRef.value.initFun(type, row);
}
function refreshList() {
  getData();
}
function statusFun(row) {
  stateApi({
    status: row.status,
    id: row.id.toString(),
  }).then(() => {
    ElMessage({
      type: "success",
      message: "修改成功！",
    });
    getData();
  });
}
function delFun(row) {
  ElMessageBox.confirm("确认删除，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delApi({
        id: row.id.toString(),
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        getData();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}

function imgSrc(path) {
  return import.meta.env.VITE_APP_BASE_API + path;
}
function initFun() {
  currentPage.value = 1;
  getData();
}
// 复制
function copyFun(row) {
  copyApi({
    id: row.id,
  }).then(() => {
    ElMessage({
      type: "success",
      message: "复制成功！",
    });

    getData();
  });
}
// 库存记录
function logFun(row) {
  router.push({
    path: "/manage/log",
    query: {
      goodsId: row.id,
    },
  });
}

// 增加库存
let addNumberRef = ref(null);
function addInventory(row) {
  addNumberRef.value.initFun(row);
}
// 导入
let uploadPageRef = ref(null);
function uploadFun() {
  uploadPageRef.value.initFun();
}
function updateList() {
  getData();
}
// 分类名称
let classOptions = ref([]);
function getClass() {
  classApi({}).then((data) => {
    classOptions.value = data;
  });
}
//
defineExpose({
  initFun,
});
onMounted(() => {
  getClass();
  getData();
});
</script>
<style scoped lang="scss">
.manage-shopping-tab1 {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;

  .manage-shopping-title {
    width: 100%;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #eeeeee;
    padding-bottom: 10px;

    .manage-shopping-title-left {
      font-size: 18px;
      font-weight: 700;
      color: #172b4d;

      :deep(.el-form-item) {
        width: calc(100% / 7 - 20px);
        margin-bottom: 0 !important;
      }
    }
  }

  .manage-shopping-table {
    box-sizing: border-box;

    .manage-info {
      display: flex;

      .img-box {
        align-self: center;
      }

      .right {
        margin-left: 10px;
        align-self: center;

        span {
          color: #409eff;
        }
      }
    }

    .manage-shopping-table-foot {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
